{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "#coding:utf-8\n",
    "import random\n",
    "import numpy as np\n",
    "import nltk.corpus as nc\n",
    "import nltk.classify as cf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "male_names = nc.names.words('male.txt')\n",
    "female_names = nc.names.words('female.txt')\n",
    "models,acs = [],[]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "for n_letters in range(1,6):\n",
    "    data = []\n",
    "    for male_name in male_names:\n",
    "        feature = {'feature':male_name[-n_letters:].lower()}\n",
    "        data.append((feature,'male'))\n",
    "    for female_name in female_names:\n",
    "        feature = {'feature':female_name[-n_letters:].lower()}\n",
    "        data.append((feature,'female'))\n",
    "    random.seed(7)\n",
    "    random.shuffle(data)\n",
    "    train_data = data[:int(len(data)/2)]\n",
    "    test_data = data[int(len(data)/2):]\n",
    "    model = cf.NaiveBayesClassifier.train(train_data)\n",
    "    ac = cf.accuracy(model,test_data)\n",
    "    models.append(model)\n",
    "    acs.append(ac)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2 77.82%\n"
     ]
    }
   ],
   "source": [
    "best_index = np.array(acs).argmax()\n",
    "best_letters = best_index + 1\n",
    "#print(best_letters)\n",
    "best_model = models[best_index]\n",
    "best_ac = acs[best_index]\n",
    "print(best_letters,'%.2f%%'%round(best_ac*100,2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "names = ['Jack']\n",
    "#print(names)\n",
    "genders = []\n",
    "for name in names:\n",
    "    feature = {'feature':name[-best_letters:]}\n",
    "    gender = best_model.classify(feature)\n",
    "    genders.append(gender)\n",
    "print(genders)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
